<!--
* description: 整车销售---订单配车
* author:xlc
* createdDate: 2020-11-19
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="true"
      :dynamic-is-show-more-btn="true"
      :callback-obj="callbackObj"
    />
    <edit
      v-if="editPopupsVisible"
      :key="editPopupsKey"
      :popups-visible="editPopupsVisible"
      :data-for-form="editRowDataArray"
      :popups-state="editPopupsState"
      :title-name="titleName"
      :isshow="isshow"
      @close="close"
      @save="save"
    />
    <switch-auto
      :key="switchPopupsKey"
      :popups-visible="switchPopupsVisible"
      @close="autoClose"
    />
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import { orgApis } from '@/api/vesalesapi.js'
import { exportExcel } from '@/utils/getTimeString.js'
import OneTableTemplate from '@/components/templates/oneTable'
import Edit from './edit'
import switchAuto from './switchAuto'
import commData from '../common/index.js'
import Vue from 'vue'
export default {
  name: 'OrderMatchCar',
  components: {
    OneTableTemplate,
    switchAuto,
    Edit
  },
  mixins: [oneTableWithViewTemplateMixins],
  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, 'supplierMessage-edit'], () => {
      next()
    })
  },

  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      titleName: '',
      editRowDataArray: [],
      switchPopupsKey: '',
      switchPopupsVisible: false,
      editPopupsState: '',
      editPopupsVisible: false,
      // 弹窗类型
      isshow: '',
      // 网格查询API配置对象
      apiConfig: orgApis.orderMatchCarQuery,
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          clickEvent: () => this.queryTable(1),
          text: this.$t('sys.button.query'), // 查询
          name: 'search', // 按钮图标样式
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey2',
          type: '',
          size: 'small',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset'),
          name: 'reset',
          position: 'right' // 重置
        },
        {
          compKey: 'btnKey3',
          type: '',
          size: 'small',
          disabled: true,
          isShow: false,
          clickEvent: () => this.showedit('batch'),
          text: '批量手工配车',
          name: 'batchSubmit',
          position: 'left'
        },
        {
          compKey: 'btnKey4',
          type: '',
          size: 'small',
          clickEvent: () => this.showedit('import'),
          text: '导入配车',
          name: 'importTemplate',
          position: 'left'
        },
        {
          compKey: 'btnKey5',
          type: '',
          size: 'small',
          clickEvent: () => this.exportExcel111(orgApis.orderMatchCarExport, '订单配车'),
          text: '导出',
          name: 'export',
          position: 'left'
        },
        {
          compKey: 'btnKey6',
          type: '',
          size: 'small',
          clickEvent: () => this.autoshow(),
          text: '自动配车',
          name: 'export',
          position: 'left'
        }
      ],
      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [ // 显示组件
            {
              compKey: 'compKey0',
              labelName: '订单状态：',
              codeField: 'orderStatus',
              lookuptype: 'VE1003',
              component: () => import('@/components/org/LookupValue'),
              type: 'dropdownList',
              isMust: true
            },
            {
              compKey: 'compKey1',
              labelName: 'DMS订单编号：',
              codeField: 'saleOrderCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true
            },
            {
              compKey: 'compKey2',
              labelName: 'C端订单编号：',
              codeField: 'saleOrderCodeC',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey3',
              labelName: '订单标签：',
              codeField: 'saleOrderSign',
              lookuptype: 'VE1013',
              component: () => import('@/components/org/LookupValue'),
              type: 'dropdownList',
              isMust: true
            },
            {
              compKey: 'compKey4',
              labelName: '客户姓名：',
              codeField: 'custName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey5',
              labelName: '客户电话：',
              codeField: 'custTel',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey6',
              labelName: '证件号码：',
              codeField: 'custCardNo',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey7',
              labelName: '购买方式：',
              codeField: 'buyTypeId',
              lookuptype: 'VE0117',
              component: () => import('@/components/org/LookupValue'),
              type: 'dropdownList',
              isMust: false
            },
            {
              compKey: 'compKey9',
              labelName: '交付门店：',
              codeField: 'deliveryDlrId',
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMust: false,
              oFields: 'deliveryDlrId,deliveryDlrShortName',
              customObj: {
                api: orgApis.ListOfDeliveryStore
              }
            },
            {
              compKey: 'compKey10',
              labelName: '交付专员：',
              codeField: 'empId',
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMust: false,
              parentFileds: 'value:deliveryDlrId',
              oFields: 'empId,empName',
              customObj: {
                listQuery: { deliveryDlrId: '' },
                api: orgApis.ListOfdeliveryPersonnel
              }
            },
            {
              compKey: 'compKey11',
              labelName: '仓库名称：',
              codeField: 'carStockHouseId',
              component: () => import('@/components/org/commonSelect'),
              customObj: { api: orgApis.ListOfCityWarehouse, selectType: '1', listQuery: { warehouseId: '1' }},
              oFields: 'stockId,stockName',
              type: 'dropdownList',
              isMust: false
            },
            {
              compKey: 'compKey12',
              labelName: '销售计划号：',
              codeField: 'salePlanCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey13',
              labelName: 'VIN码：',
              codeField: 'vin',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: false
            },
            ...commData.ModelOptions()
          ],
      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'controlBtn',
              label: '操作', // 操作
              codeField: 'controlBtn',
              width: 100,
              fixed: true,
              align: 'center',
              isComponent: true,
              comps: [
                {
                  compKey: 'propKey1',
                  labelName: '配车', // 编辑
                  align: 'center',
                  codeField: 'editControlBtn',
                  clickEvent: index => { this.showcar(index) },
                  rowFileds: 'show:orderStatus-6',
                  component: () => import('@/components/org/linkButton')
                },
                {
                  compKey: 'propKey2',
                  labelName: '解配', // 编辑
                  align: 'center',
                  rowFileds: 'show:orderStatus-8',
                  codeField: 'editControlBtn',
                  clickEvent: index => { this.reject(index) },
                  component: () => import('@/components/org/linkButton')
                }
              ]
            },
            {
              prop: 'saleOrderCode',
              label: 'DMS订单编号',
              width: 120
            },
            {
              prop: 'saleOrderCodeC',
              label: 'C端订单编号',
              width: 120
            },
            {
              prop: 'orderStatus',
              label: '订单状态', width: 120,
              hidden: true
            },
            {
              prop: 'orderStatusName',
              label: '订单状态', width: 120
            },
            {
              prop: 'twentyTwoCode',
              label: '22位码', width: 180
            },
            {
              prop: 'saleOrderSignName',
              label: '订单标签', width: 120
            },
            {
              prop: 'salePlanCode',
              label: '销售计划号', width: 120
            },
            {
              prop: 'vin',
              label: 'VIN码', width: 160
            },
            {
              prop: 'carHouseName',
              label: '仓库名称', width: 120
            },
            {
              prop: 'receivedAmount',
              label: '已收金额', width: 120
            },
            {
              prop: 'custName',
              label: '客户姓名', width: 120
            },
            {
              prop: 'custTel',
              label: '客户电话', width: 120
            },
            {
              prop: 'custCardName',
              label: '证件类型', width: 120
            },
            {
              prop: 'custCardNo',
              label: '证件号码', width: 160
            },
            {
              prop: 'custLxName',
              label: '联系人姓名', width: 120
            },
            {
              prop: 'custLxPhone',
              label: '联系人电话', width: 120
            },
            {
              prop: 'buyTypeName',
              label: '购买方式', width: 120
            },
            {
              prop: 'buyUserName',
              label: '购买用途', width: 120
            },
            {
              prop: 'buyModelName',
              label: '购买形态', width: 120
            },
            {
              prop: 'reserveDate',
              label: '下单日期', width: 180
            },
            {
              prop: 'caEmpName',
              label: '销售人员', width: 120
            },
            {
              prop: 'caEmpPhone',
              label: '销售人员电话', width: 120
            },
            {
              prop: 'crmPreDeliverDate',
              label: '预计交付日期', width: 180
            },
            {
              prop: 'cityName',
              label: '交付城市', width: 120
            },
            {
              prop: 'dlrShortName',
              label: '交付门店', width: 120
            },
            {
              prop: 'storeCategory',
              label: '门店类别', width: 120
            },
            {
              prop: 'empName',
              label: '交付专员', width: 120
            },
            {
              prop: 'carSeriesCn',
              label: '车系名称', width: 120
            },
            {
              prop: 'carConfigCn',
              label: '基础车型名称', width: 120
            },
            {
              prop: 'optionalPag',
              label: '选装包', width: 120
            },
            {
              prop: 'carColorName',
              label: '车身颜色', width: 120
            },
            {
              prop: 'carIncolorName',
              label: '内饰颜色', width: 120
            }
          ],
      formField: {
        orderStatus: '',
        saleOrderCode: '',
        saleOrderCodeC: '',
        saleOrderSign: '',
        custName: '',
        custTel: '',
        custCardNo: '',
        buyTypeId: '',
        deliveryDlrId: '',
        deliverEmpId: '',
        carStockHouseId: '',
        salePlanCode: '',
        vin: '',
        carSeriesId: '',
        carConfigId: '',
        optionalPagId: '',
        empId: '',
        carColorId: '',
        carIncolorId: ''
      },
      // 是否使用刷新Key的方式刷新弹窗
      resetDialogKey: false,
      // 单表格模版页面组件回调事件
      callbackObj: {
        // 当选择项发生变化时会触发该事件（多选时）
        onCheckSelectChange: (selection) => {
          this.editRowDataArray = selection
          this.onCheckSelectChange1(selection)
        }
      }
    }
  },
  mounted() {
    this.queryTable(1)
  },
  methods: {
    // 解配
    reject(index) {
      this.$refs['multipleTable'].listLoading = true
      const that = this
      var {
        DLR_ID,
        saleOrderId,
        updateControlIdD,
        updateControlId,
        saleOrderDate,
        custType,
        saleOrderCodeC,
        carSeriesCode,
        carConfigCode,
        optionalPagCode,
        carIncolorCode,
        carColorCode,
        ASSIGN_DATE,
        isVip,
        dlrCode,
        vin,
        salePlanCode
      } = this.$refs.multipleTable.list[index]
      const queryObj = {
        // api配置
        apiConfig: orgApis.orderMatchCarRemove,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          // 当前中台使用的名称有dataInfo、info，具体查看API文档
          dataInfo: {
            DLR_ID,
            isVip,
            dlrCode,
            saleOrderId,
            updateControlIdD,
            updateControlId,
            saleOrderDate,
            custType,
            saleOrderCodeC,
            carSeriesCode,
            carConfigCode,
            optionalPagCode,
            carIncolorCode,
            carColorCode,
            ASSIGN_DATE,
            vin,
            salePlanCode
          }
        }
      }
      // 转换了中台请求格式数据
      var paramD = that.$getParams(queryObj)
      // 调用中台API方法（可复用）
      that.$requestAPI(paramD).then(response => {
        this.$refs['multipleTable'].listLoading = false
        this.$message({
          message: response.msg,
          duration: 2000
        })
        if (response.result === '1') {
          this.queryTable(1)
        }
      })
    },
    // 自动配车开关
    autoshow() {
      this.switchPopupsVisible = true
    },
    autoClose(type) {
      this.switchPopupsVisible = false
      if (type === '1') {
        this.queryTable()
      }
    },
    // ?
    save(data) {
      this.$refs['multipleTable'].listLoading = true
      const that = this
      const queryObj = {
        // api配置
        apiConfig: orgApis.orderMatchCarConfirm,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          // 当前中台使用的名称有dataInfo、info，具体查看API文档
          dataInfo: data
        }
      }
      // 转换了中台请求格式数据
      var paramD = that.$getParams(queryObj)
      // 调用中台API方法（可复用）
      that.$requestAPI(paramD).then(response => {
        this.$message({
          message: response.msg,
          duration: 2000
        })
        if (response.result === '1') {
          this.$refs['multipleTable'].listLoading = false
          this.close('1')
        }
      })
    },

    // 导出
    exportExcel111(api, title) {
      exportExcel(this.formField, api.APIUrl, api.ServiceCode, title)
    },

    // 按钮disabled控制
    onCheckSelectChange1(selection) {
      var btns = this.tableButtons[2]
      const isCheck = selection && selection.length > 0
      btns.disabled = !isCheck
    },

    // 选择列checkbox是否生效
    getSelectable(row, index) {
      return row.orderStatus === '6'
    },
    // 手动配车
    showcar(index) {
      this.titleName = '手动配车'
      this.isshow = 'car'
      this.editPopupsVisible = true
      this.editRowDataArray[0] = this.$refs.multipleTable.list[index]
    },
    // 显示批量导入
    showedit(data) {
      this.editPopupsVisible = true
      this.isshow = data
      if (data === 'batch') {
        this.titleName = '批量手工配车'
      } else if (data === 'import') {
        this.titleName = '导入配车'
      }
    }
  }
}
</script>
